package com.ruoyi.common.xss

import java.util.regex.Pattern
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext

/**
 * 自定义xss校验注解实现
 *
 * @author ruoyi
 */
class XssValidator : ConstraintValidator<Xss?, String?> {
    override fun isValid(value: String?, constraintValidatorContext: ConstraintValidatorContext): Boolean {
        return if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
            true
        } else !containsHtml(value)
    }

    companion object {
        private const val HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />"
        fun containsHtml(value: String?): Boolean {
            val sHtml = StringBuilder()
            val pattern = Pattern.compile(HTML_PATTERN)
            val matcher = pattern.matcher(value)
            while (matcher.find()) {
                sHtml.append(matcher.group())
            }
            return pattern.matcher(sHtml).matches()
        }
    }
}
